<!-- 终端列表 -->
<template>
  <view class="container">
    <view class="top-bg">
      <u-sticky>
        <view class="return" @click="goToBack()">
          <u-icon name="arrow-left" color="#ffffff " bold="true" size="38"></u-icon>
        </view>
        终端总数
        <!-- 切换2 二级 -->
        <van-tabs color="#fff" title-active-color="#fff" disabled title-inactive-color="rgba(255,255,255, 0.8)" class="checkTab"
          :active="checkedItem" @change="onChange">
          <van-tab title="全部终端">
            <!-- 筛选条件-全部终端 二级 -->
            <van-dropdown-menu v-if="checkedItem ===0" active-color="#2769F7" custom-class="dorpdownClass"
              :use-before-toggle="true" @before-toggle="beforeToggle">
              <van-dropdown-item id="areaRef" @open="open" @change="beforeToggle('#areaRef')" title="区域"
                :value="queryParams.areaId">
                <!-- <van-cell @click="clickItem(item,true)" v-for="item in paramsList.areaList" :key="item.id" :title="item.departName">
                <image v-if="clickedCellArea.includes(item.id)" src="@/static/terminal/yes.png" style="width: 37rpx;height: 27rpx;vertical-align: middle;"></image>
              </van-cell> -->
                <!-- <TreeItem v-for="(item,index) in treeData" :key="item.id" :node="item" @clickNode="clickNode"/> -->
                <!-- <van-tree-select
                :items="dataTree"
                :main-active-index="mainActiveIndex"
                :active-id="activeId"
                @click-nav="onClickNav"
                @click-item="onClickItem"
              /> -->

                <!-- <view style="padding: 5px 16px;text-align: center;">
                <van-button @click="resetQueryParams('area')" custom-style="width: 45%;margin-right: 20rpx" color="rgba(0, 204, 116, 1)" plain type="danger" round>
                  重置
                </van-button>
                <van-button custom-style="width: 45%" color="rgba(0, 204, 116, 1)" type="danger" round @click="onConfirm('area')">
                  确认
                </van-button>
              </view> -->
              </van-dropdown-item>
              <van-dropdown-item id="statusRef" @change="beforeToggle('#statusRef')" title="状态"
                :value="queryParams.status">
                <van-cell @click="clickItem(item,false)" v-for="item in paramsList.statusList" :key="item.value"
                  :title="item.text">
                  <!-- <image v-if="clickedCellStatus.includes(item.text)" src="@/static/terminal/yes.png"
                    style="width: 37rpx;height: 27rpx;vertical-align: middle;"></image> -->
                  <van-icon v-if="clickedCellStatus.includes(item.value)" name="success"
                    style="font-size: 37rpx;color: #3C8AFF" />
                </van-cell>
                <view style="padding: 5px 16px;text-align: center;">
                  <van-button @click="resetQueryParams('status')" custom-style="width: 45%;margin-right: 20rpx"
                    color="#3C8AFF" plain type="danger" round>
                    重置
                  </van-button>
                  <van-button custom-style="width: 45%" color="#3C8AFF" type="danger" round
                    @click="onConfirm('status')">
                    确认
                  </van-button>
                </view>
              </van-dropdown-item>
            </van-dropdown-menu>
            <!-- 终端列表 通用 -->
            <view class="listContent">
              <uni-card v-show="!checkedItem || checkedItem ===0" v-for="item in terminalList" :key="item.terminalId" 
                shadow="0rpx 3rpx 15rpx 0rpx rgba(0,14,17,0.04)" padding="0">
                <template v-slot:title>
                  <view class="terminalTitle">
                    <view class="left" @click="toTerminalDetail(item)">
                      <span style="letter-spacing: 0;"><span class="titleIcon"></span>{{item.terminalName}}</span>
                       <!-- @click="todetail(item)" -->
                      <van-button type="info" size="small"
                        style="margin-left: 24rpx">查看详情</van-button>
                    </view>
                    <view class="right">
                      <!-- 1-运行  2-未运行-->
                      <van-tag class="tagsItem" size="medium" :color="item.terminalStatus === 1 ? '#E5EEFF' : '#E1E1E1'"
                        :text-color="item.terminalStatus === 1 ? '#3C8AFF': '#8E8E8E'">
                        {{ ['运行中','未运行'][item.terminalStatus - 1] }}
                      </van-tag>
                      <van-tag class="tagsItem" size="medium" :color="item.equipmentAlarm === 1 ? '#D5EFE7' : '#FFEBEF'"
                        :text-color="item.equipmentAlarm === 1 ? '#74CDAF': '#FC8382'">
                        {{ ['正常','异常'][item.equipmentAlarm - 1] }}
                      </van-tag>
                    </view>
                  </view>
                </template>
                <view class="uni-body">
                  <view class="areaList">
                    <!-- <view class="areaItem" >{{item.regionName}}</view> -->
                    <view class="areaItem" v-for="(region,index) in item.departName.split(',')" :key="index">{{region}}
                    </view>
                  </view>
                  <view class="deviceInfo">
                    <!-- @click="todetail(item,equ)" -->
                    <view class="device-content" v-for="(equ,index) in item.equipmentList" :key="index"
                      >

                      <view class="deviceItem">
                        <view>{{equ.equTypeName}}</view>
                        <!-- equ.policeType === '超标' ? require('@/static/terminal/icon-超标.png') : -->
                        <image
                          :src="equ.policeType === 0 ? require('@/static/terminal/icon-正常.png') :
                                      equ.policeType === 1 ?  require('@/static/terminal/icon-离线.png') : require('@/static/terminal/icon-损坏.png')"
                          style="width: 28rpx;height: 28rpx;"></image>
                        <view>{{policeTypeList[equ.policeType]}}</view>
                      </view>
                      <view class="rightLine"></view>
                    </view>

                  </view>
                </view>
              </uni-card>
            </view>
          </van-tab>
          <!-- 能耗排行tab 二级 -->
          <!-- <van-tab title="" disabled>
            <Ranking v-show="checkedItem === 1" :regionId="queryParams.areaId" />
          </van-tab> -->
        </van-tabs>
      </u-sticky>

      <!-- <view v-if="!!checkedItem" class="checkTab" style="justify-content: center;">
        <view class="checkItem" @click="checkedItem = 'all'">
          <view :class="checkedItem !== 'all' ? 'unchecked':''">
            全部终端
          </view>
          <image v-if="checkedItem==='all'" src="@/static/terminal/selectedBottom.png" class="selectedBottom"></image>
        </view>
        <view class="checkItem" @click="checkedItem = 'ranking'">
          <view :class="checkedItem !== 'ranking' ? 'unchecked':''">
            能耗排行
          </view>
          <image v-if="checkedItem==='ranking'" src="@/static/terminal/selectedBottom.png" class="selectedBottom">
          </image>
        </view>
      </view> -->

    </view>

    <Tree ref="tree" :range="dataTree" rangeKey="departName" idKey="id" title="区域筛选" @confirm="treeConfirm"
      @cancel="treeCancel" />

  </view>
</template>

<script>
// import Ranking from './ranking.vue'
// import TreeItem from '@/components/Tree-Item'
import Tree from '@/subpack_Manage_Terminal/components/TreeSelect';
// import { getUserDepartList } from '@/api/login'
import { getAreaTreeList } from '@/api/area'
import { getTerminalList } from '@/api/terminal'
import { searchTree } from '@/utils/treeOperate'

import { getManageTerminal } from '@/api/manage'
export default {
  components: { Tree },
  data() {
    return {
      policeTypeList:{0: '正常',1:'离线',2:'异常',3:'液位',4:'水质(氨氮)',5:'渗透率',6:'流量',7:'水质(PH)',8:'水质(COD)',12:'阈值报警'},
      clickedCellArea: [],
      clickedCellStatus: [],
      terminalList: [],
      userDepartList: [],
      dataTree: [],
      treeData: [],
      mainActiveIndex: 0,
      activeId: 0,
      queryParams: {
        status: [],
        areaId: '',
        // pageNo: 1,
        // pageSize: 100
      },
      paramsList: {
        areaList: [
          { text: '全部商品', value: 0 },
          { text: '新款商品', value: 1 },
          { text: '活动商品', value: 2 },
        ],
        statusList: [
          { text: '正常', value: 1 },
          { text: '异常', value: 2 },
          { text: '运行', value: 3 },
          { text: '未运行', value: 4 },
        ],
      },
      checkedItem: 0, //根据身份判断 三级为空 二级为all 或者ranking
      status: 1, // 判断终端状态标签背景展示 true为正常 false为异常
      areaList: [
        { id: 1, name: '村庄1' },
        { id: 2, name: '村庄2' },
        { id: 3, name: '村庄3' }
      ],
      statusBg: ''
    }
  },
  onLoad(query) {
    const { areaId } = query
    this.queryParams.areaId = areaId
    // if (uni.getStorageSync('orgType') === '6') {
    //   this.checkedItem = false
    // }
  },
  onShow() {
    //⭐隐藏pages.json里配置的导航栏，使用封装的tabbar组件
    uni.hideTabBar({
      animation: false
    })

  },
  mounted() {
    // 添加区域查询字段
    // this.queryParams.areaId = uni.getStorageSync('regionId')
    this.getTerminalList()
    // this.getUserDepartList()
    this.getAreaTree()
  },
  methods: {
    toTerminalDetail(item) { 
      const selectData = JSON.stringify(item)
      console.log('点击跳转', item, selectData)
      uni.navigateTo({url: `/subpack_Manage_Terminal/terminal/terminalDetail?selectData=${selectData}`})
    },
    onChange(e) {
      this.checkedItem = e.detail.index
      console.log(e.detail, this.checkedItem, 'e.detail')
    },

    goToBack() {
      uni.navigateBack()
    },
    open() {
      this.$refs.tree._show()
    },
    /**
     * 点击确定
     */
    treeConfirm(e) {
      console.log(e)
      this.selectComponent('#areaRef').toggle(false);
      // 其他业务逻辑
      if (e.length) {
        this.clickItem(e[0], true)
        this.onConfirm('area')
      }
    },

    /**
     * 点击取消
     */
    treeCancel(e) {
      console.log(e)
      this.selectComponent('#areaRef').toggle(false);
    },

    clickNode(node) {
      this.filterData1(this.treeData, node.departName)
      console.log('click', this.treeData, node)
    },
    /** 获取区域树 */
    async getAreaTree() {
      const res = await getAreaTreeList()
      this.dataTree = res.data.data
      this.treeData = this.filterData(this.dataTree, '')
      console.log(this.treeData)
      // 使用函数查找值为'grandchild1_1'的节点
      const foundNode = searchTree(res.data.data[0], uni.getStorageSync('regionId'));
      this.paramsList.areaList = foundNode.children
      console.log(foundNode, foundNode.children, this.paramsList.areaList); // 输出匹配的节点对象
      console.log(this.dataTree, uni.getStorageSync('regionId'), 'tree')
    },

    //筛选出符合条件的数据
    filterData(data, keyword) {
      return data.filter(node => {
        // 判断当前节点是否匹配筛选条件
        if (node.departName.includes(keyword)) {
          if (node.children && node.children.length) {
            // if (!node.type) {
            node.isOpen = true
          }
          return true;
        }
        // 递归过滤子节点
        if (node.children && node.children.length) {
          node.children = this.filterData(node.children, keyword);
          node.isOpen = true
          return node.children.length > 0;
        }
        return false;
      });
    },
    filterData1(data, keyword) {
      console.log(keyword, 'word')
      for (let item of data) {
        // data.forEach(item => {
        if (item.departName === keyword) {
          if (item.children && item.children.length) {
            item.isOpen = !item.isOpen
            console.log(item.children, 'item.children')
            for (let child of item.children) {
              console.log(child, 'child')
              if (child.children && child.children.length) {
                this.$set(child, 'isOpen', item.isOpen)
                // child.isOpen = true
              }
            }
          }
        } else {
          // 递归操作子节点
          if (item.children && item.children.length) {
            this.filterData1(item.children, keyword);
          }
        }
        // })
      }
    },
    /** 获取用户负责的区域 */
    // async getUserDepartList() {
    //   const userId = uni.getStorageSync('userId')
    //   const res = await getUserDepartList({ userId })
    //   this.paramsList.areaList = res.data.result
    // },
    resetQueryParams(type) {
      if (type === 'status') {
        this.queryParams.status = []
        this.clickedCellStatus = []
        this.selectComponent('#statusRef').toggle(false)
      }
      if (type === 'area') {
        this.queryParams.areaId = ''
        this.clickedCellArea = []
      }
      this.getTerminalList()
    },
    onConfirm(type) {
      if (type === 'status') {
        this.queryParams.status = this.clickedCellStatus
        this.selectComponent('#statusRef').toggle(false)
        console.log(this.clickedCellStatus, 'clickedCellStatus')
      }
      if (type === 'area') {
        this.queryParams.areaId = this.clickedCellArea[0]
        console.log(this.clickedCellArea[0], this.clickedCellArea, 'this.clickedCellArea[0]')
      }
      this.getTerminalList()
    },
    /** 获取终端设备列表 */
    async getTerminalList() {
      // const { data: { data } } = await getTerminalList(this.queryParams)
      // this.terminalList = data.records

      getManageTerminal(this.queryParams).then(({ data }) => {
        this.terminalList = data.data
      })
    },
    /** 自定义筛选下拉的选中取消逻辑 */
    clickItem(item, type) {
      if (type) {
        if (this.clickedCellArea.includes(item.id)) {
          this.clickedCellArea.splice(this.clickedCellArea.indexOf(item.id), 1)
        } else {
          this.clickedCellArea = []
          this.clickedCellArea.push(item.id)
        }
      } else {
        if (this.clickedCellStatus.includes(item.value)) {
          this.clickedCellStatus.splice(this.clickedCellStatus.indexOf(item.value), 1)
        } else {
          this.clickedCellStatus.push(item.value)
        }
      }
    },
    beforeToggle(refName) {
      console.log(refName, this.selectComponent(refName), this.selectComponent(refName).toggle, 'change了')
      // this.selectComponent(refName).toggle(false)
    },
    todetail(item, equ) {
      if (equ) {
        this.$tab.navigateTo(`/subpack_TerminalDevice/terminal/detail/index?terminalId=${item.terminalId}&terminalName=${item.terminalName}&id=${item.id}&equType=${equ.equType}`)
      } else {
        this.$tab.navigateTo(`/subpack_TerminalDevice/terminal/detail/index?terminalId=${item.terminalId}&terminalName=${item.terminalName}&id=${item.id}`)
      }
    },
    onClickNav(e) {
      console.log(e, 'eeeeee')
    },
    onClickItem(e) {
      console.log(e, 'eeeeee')
    },
  }
}
</script>

<style lang="scss">
.container {
  // height: calc(100vh - 220rpx);
  height: 100vh;
  overflow: scroll;
  white-space: inherit;
  font-family: PingFang-SC, PingFang-SC;
  ::v-deep .van-dropdown-menu__item {
    background: #2769f7;
    justify-content: flex-start;
    color: #fff;
    padding-left: 16rpx;
    .van-dropdown-menu__title {
      color: #fff;
    }
  }
  .top-bg {
    width: 100%;
    height: 330rpx;
    background: #2769f7;
    border-radius: 0rpx 0rpx 140rpx 140rpx;
    padding-top: 104rpx;
    text-align: center;
    font-weight: 600;
    font-size: 40rpx;
    color: #ffffff;
    letter-spacing: 4rpx;
    position: relative;
    .return {
      position: absolute;
      left: 32rpx;
      margin-top: 8rpx;
    }
    .listContent {
      height: calc(100vh - 382rpx);
      overflow-y: scroll;
    }
  }
  ::v-deep .uni-card {
    margin-top: 0 !important;
    border-radius: 20rpx !important;
    .uni-body {
      padding: 0 !important;
      text-align: left;
      display: flex;
      letter-spacing: 0;
    }
  }
  .checkTab {
    padding: 30rpx;
    padding-bottom: 0;
    margin-top: 16rpx;
    // display: flex;
    letter-spacing: 0;
    ::v-deep .van-tabs__line {
      width: 32rpx !important;
      height: 4rpx;
      border-radius: 6rpx;
      // left: 50%;
      // transform: translate(-50%, 0) !important;
    }
    ::v-deep .van-tabs__scroll {
      background-color: transparent;
      // width: 50%;
    }
    .checkItem {
      margin-right: 77rpx;
      position: relative;
      font-size: 32rpx;
      .selectedBottom {
        width: 150rpx;
        height: 16rpx;
        position: absolute;
        bottom: -10rpx;
        left: -8rpx;
        z-index: -1;
      }
    }
    .unchecked {
      color: rgba(0, 0, 0, 0.7);
    }
  }
  .terminalTitle {
    --button-small-min-width: 140rpx;
    --button-small-height: 42rpx;
    --button-border-radius: 6rpx;
    --button-info-background-color: #2769f7;

    padding-bottom: 16rpx;
    display: flex;
    margin: 20rpx 0;
    line-height: 60rpx;
    width: 100%;
    justify-content: space-between;
    color: #4a4a4a;
    font-size: 28rpx;
    border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
    flex-wrap: wrap;
    letter-spacing: 0;
    .left {
      text-align: left;
      white-space: nowrap;
    }
    .right {
      // text-align: left;
    }
    .tagsItem {
      margin-left: 12rpx;
    }
    .titleIcon {
      display: inline-block;
      width: 8rpx;
      height: 20rpx;
      background: #2769f7;
      border-radius: 6rpx 6rpx 6rpx 6rpx;
      opacity: 0.6;
      margin-right: 14rpx;
      
    }
    .statusTag {
      width: 87rpx;
      height: 34rpx;
      display: inline-block;
      background-repeat: no-repeat;
      background-size: 87rpx 34rpx;
      font-size: 20rpx;
      color: #ffffff;
      line-height: 34rpx;
      text-align: center;
      padding-left: 8rpx;
      margin-left: 16rpx;
      margin-right: 10rpx;
    }
    // .statusBgNormal {
    //   background-image: url('');
    // }
    // .statusBgAbnormal {
    //   background-image: url('');
    // }
  }
  .areaList {
    // font-size: 26rpx;
    // color: rgba(0, 222, 125, 0.7);
    color: #3c8aff;
    padding: 20rpx 0;
    .areaItem {
      // background-color: rgba(0, 222, 125, 0.05);
      background: rgba(60, 138, 255, 0.14);
      display: inline-block;
      // background: #ffffff;
      // height: 45rpx;
      border-radius: 6rpx;
      // border: 1px solid rgba(0, 222, 125, 0.3);
      border: 1rpx solid #3c8aff;
      line-height: 34rpx;
      vertical-align: middle;
      padding: 10rpx 22rpx;
      margin-right: 20rpx;
    }
  }
  .deviceInfo {
    flex: 2;
    display: flex;
    justify-content: space-around;
    margin: 32rpx 0;
    .device-content {
      display: flex;
      align-items: center;
      flex: 1;
      .rightLine {
        width: 2rpx;
        height: 32rpx;
        background: #ebebeb;
        vertical-align: middle;
      }
    }
    .deviceItem {
      width: 100%;
      // border-right: 1rpx solid rgba(7, 225, 130, 0.2);
      text-align: center;
      image {
        margin-top: 10rpx;
      }
    }
    :last-child {
      border: 0;
      .rightLine {
        display: none;
      }
    }
  }

  .dorpdownClass {
    background: transparent;
    box-shadow: none !important;
    padding-left: 30rpx;
    height: auto;
    margin-bottom: 16rpx;
    margin-top: 16rpx;
    text-align: left;
    font-family: PingFang-SC, PingFang-SC;

    ::v-deep .van-dropdown-menu__item {
      flex: 0 1 auto !important;
      padding: 10rpx 26rpx;
      border-radius: 34rpx;
      background: #f2f6f7;
      margin-right: 16rpx;
    }
    ::v-deep .van-dropdown-menu__title {
      font-size: 24rpx;
      color: #989898;
      line-height: 34rpx;
    }
  }
}
</style>